import {getCache, m7Language} from './m7Utils.js'
import store from '@/store/index'
/*
* 通话技能组签入座席渲染
* */
export function ctiUiGetQueuePeer (item, state) {
  let session = state.session
  let queue = window.phone_queues[item.queueId]
  let members
  let curPeer
  let tipTitle = ''
  if (queue) {
    members = queue.members
    let hasNoName = false
    for (var j in members) {
      curPeer = ctiGetUserFromSip(j)
      if (curPeer && session.user.type !== 'admin' && session.user.scope.call !== 'all') {
        var isFind = false
        var lowUsers = session.user.moduleUsers.call
        for (var i = 0; i < lowUsers.length; i++) {
          if (lowUsers[i] === curPeer.userId) {
            isFind = true
            break
          }
        }
        if (!isFind) {
          hasNoName = true
          continue
        }
      }
      if (curPeer != null) {
        tipTitle += (curPeer.DisplayName + ',')
      } else {
        hasNoName = true
      }
    }
    if (tipTitle !== '') {
      if (hasNoName) {
        tipTitle = '(' + tipTitle + '...)'
      } else {
        tipTitle = '(' + tipTitle.substring(0, tipTitle.lastIndexOf(',')) + ')'
      }
    } else {
      if (hasNoName) {
        tipTitle = '(...)'
      }
    }
  }
  return tipTitle
}

export function ctiGetUserFromSip (sipNo) {
  var peer = window._phone_peersFromSip[sipNo]
  if (peer === null || peer === '') {
    if (!window.phone_peers) {
      return null
    }
    for (var i in window.phone_peers) {
      if (window.phone_peers[i].sipNo === sipNo) {
        return window.phone_peers[i]
      }
    }
    return null
  } else {
    return peer
  }
}
/*
 * 多渠道技能组签入座席渲染
 * */
export function imMonitorGetQueueAgents (queue, newFlag) {
  if (!queue.onlineAgents) {
    imMonitorInitQueueAgents(queue)
  }
  let str = '0'
  if (queue.onlineAgents.length > 0) {
    str = queue.onlineAgents.length + '('
    for (let i = 0; i < queue.onlineAgents.length; i++) {
      str += queue.onlineAgents[i].name
      if (i !== queue.onlineAgents.length - 1) {
        str += ','
      }
    }
    if (newFlag) {
      var array = str.split('(')
      var nstr = array[1]
      return nstr
    }
    str += ')'
  }
  return str
}
/*
 * 多渠道技能组签入座席，开启自动领取座席初始化
 * */
export function imMonitorInitQueueAgents (queue) {
  // var onlines = store.dispatch('getCache', {type: 'onlineChannelAgent', loadFromServer: true})
  var onlines = getCache('onlineChannelAgent') || []
  let resultList = []
  let members = queue.AssignMembers || []
  for (var i = 0; i < members.length; i++) {
    var curId = queue.AssignMembers[i].agentID
    for (var j = 0; j < onlines.length; j++) {
      var agent = onlines[j]
      if (agent._id === curId) {
        var agentInfo = store.state.monitor.table.agentMonitor[curId]
        if (!agentInfo) {
          agentInfo = {displayName: ''}
        }
        if (!agentInfo.displayName) {
          agentInfo.displayName = ''
        }
        var tmpAgent = {id: curId, name: agentInfo.displayName, autoClaim: agentInfo.autoClaim}
        resultList.push(tmpAgent)
      }
    }
  }
  store.commit('monitor/MULTI_SKILL_CHECK_INIT', {key: queue.Exten, onlineAgents: resultList})
}
/*
 * 座席接听方式
 * */
export function ctiUiDisplayExtenType (peer) {
  let displayExtenType = ''
  if (peer.extenType === 'sip') {
    displayExtenType = m7Language('monitor.softPhone')
  } else if (peer.extenType === 'gateway') {
    displayExtenType = m7Language('cti.SipPhone')
  } else if (peer.extenType === 'Local') {
    displayExtenType = peer.localNo
  } else if (peer.extenType === 'none') {
    displayExtenType = m7Language('monitor.noPhoneJoin')
  }
  return displayExtenType
}
/*
 * 座席当前状态
 * */
export function ctiUiDisplayStatus (peer, ctiUiDesc, phoneData) {
  let displayName = {color: '', content: '', state: ''}
  if (peer.login && peer.extenType !== 'none') {
    if ((peer.extenType === 'sip' || peer.extenType === 'gateway') && peer.register === false) {
      displayName = {color: '', content: ctiUiDesc['unregister'], state: 'unregister'}
    } else if (peer.callStatus === 'Idle') {
            // console.info(phone_data.phonebarConfig[peer.busyType]);
      let phonebarConfig = phoneData.phonebarConfig || {}
      if (peer.busyType === '0') {
        displayName = ctiUiGetColor(phonebarConfig[peer.busyType], '0', peer.busyType)
      } else {
        displayName = ctiUiGetColor(phonebarConfig[peer.busyType], '1', peer.busyType)
      }
    } else if (peer.callStatus === 'Ring') {
      displayName = ctiUiGetColor(ctiUiDesc['dialing'], '2')
    } else if (peer.callStatus === 'Ringing') {
      displayName = ctiUiGetColor(ctiUiDesc['belling'], '2')
    } else if (peer.callStatus === 'inner') {
      displayName = ctiUiGetColor(ctiUiDesc['innerTalking'], '2')
    } else if (peer.callStatus === 'normal') {
      displayName = ctiUiGetColor(ctiUiDesc['talking'], '2')
    } else if (peer.callStatus === 'dialout') {
      displayName = ctiUiGetColor(ctiUiDesc['dialTalking'], '2')
    } else if (peer.callStatus === 'dialTransfer') {
      displayName = ctiUiGetColor(ctiUiDesc['dialTransfer'], '2')
    } else if (peer.callStatus === 'transfer') {
      displayName = ctiUiGetColor(ctiUiDesc['transfer'], '2')
    } else if (peer.callStatus === 'listen') {
      displayName = ctiUiGetColor(ctiUiDesc['listened'], '2')
    }
    // validate?
  } else if (peer.login && peer.extenType === 'none') {
    displayName = {color: '', content: ''}
  } else {
    if (peer.callStatus === 'Ring') {
      displayName = ctiUiGetColor(ctiUiDesc['dialing'], '2')
    } else if (peer.callStatus === 'Ringing') {
      displayName = ctiUiGetColor(ctiUiDesc['belling'], '2')
    } else if (peer.callStatus === 'inner') {
      displayName = ctiUiGetColor(ctiUiDesc['innerTalking'], '2')
    } else if (peer.callStatus === 'normal') {
      displayName = ctiUiGetColor(ctiUiDesc['talking'], '2')
    } else if (peer.callStatus === 'dialout') {
      displayName = ctiUiGetColor(ctiUiDesc['dialTalking'], '2')
    } else if (peer.callStatus === 'dialTransfer') {
      displayName = ctiUiGetColor(ctiUiDesc['dialTransfer'], '2')
    } else if (peer.callStatus === 'transfer') {
      displayName = ctiUiGetColor(ctiUiDesc['transfer'], '2')
    } else if (peer.callStatus === 'listen') {
      displayName = ctiUiGetColor(ctiUiDesc['listened'], '2')
    } else {
      if (!peer.login && (peer.extenType === 'gateway' || peer.extenType === 'Local' || peer.extenType === 'sip')) {
        displayName = {color: '', content: ctiUiDesc['offline'], state: 'offline'}
      } else {
        displayName = {color: '', content: ctiUiDesc['ready'], state: 'ready'}
      }
    }
  }
  return displayName
}
/*
 * 座席当前状态颜色
 * */
function ctiUiGetColor (content, type, state) {
  if (type === '0') {
    return {color: 'cdr-green', content: content, state}
  } else if (type === '1') {
    return {color: 'cdr-red', content: content, state}
  } else if (type === '2') {
    return {color: 'cdr-orange', content: content, state: 'calling'}
  } else {
    return {color: '', content: content}
  }
}
/*
 * 领取开关显示
 * */
export function renderAutoClaimDispaly (status) {
  if (status === undefined) {
    return ''
  } else if (status === true) {
    return 'public.open'
  } else if (status === false) {
    return 'public.close'
  }
}
/*
 * 座席监控里操作按钮的显示隐藏
 * */
export function ctiUicontrolMonitor (peer, phoneData, state) {
  let dataDisabled = {}
  dataDisabled.changeState = {disabled: true, show: true}
  if (peer.login && peer.extenType !== 'none' && !state.session.user.isAdmin && peer.register) { // 已登录 && 有登录方式 && 不是超管 && 电话条有登录
    if (peer.callStatus === 'Idle' && ((peer.busyType >= 0 && peer.busyType <= 9) || peer.busyType === '99') && peer.userId !== phoneData.userId && state.session.user.type === 'manager') { // 注册上 && （状态0-9 || 后处理） && 不是自己 && 是监控座席
      dataDisabled.changeState = {disabled: false, show: true}
    } else {
      dataDisabled.changeState = {disabled: true, show: true}
    }
  } else {
    dataDisabled.changeState = {disabled: true, show: true}
  }
  if (peer.userId === phoneData.userId || (!peer.login && peer.extenType !== 'Local' && peer.extenType !== 'gateway' && peer.extenType !== 'sip')) {
    dataDisabled.kick = {disabled: true, show: true}
  } else {
    dataDisabled.kick = {disabled: false, show: true}
  }
  if (peer.userId === phoneData.userId || peer.login || (!peer.login && peer.extenType === 'Local') || (!peer.login && peer.extenType === 'gateway')) {
    dataDisabled.pick = {disabled: true, show: true}
    dataDisabled.pickGateway = {disabled: true, show: true}
  } else {
    dataDisabled.pick = {disabled: false, show: true}
    dataDisabled.pickGateway = {disabled: false, show: true}
  }
  if (peer.callStatus !== 'listen' && peer.callStatus !== 'Idle') {
    dataDisabled.forceHangup = {disabled: false, show: true}
  } else {
    dataDisabled.forceHangup = {disabled: true, show: true}
  }
  if (phoneData.extenType === 'none' || peer.userId === phoneData.userId || ctiUiIsCalling(phoneData.userId) || !ctiUiIsCalling(peer.userId)) {
    dataDisabled.loot = {disabled: true, show: true}
  } else {
    dataDisabled.loot = {disabled: false, show: true}
  }
  if (phoneData.extenType !== 'none' && peer.userId !== phoneData.userId && !ctiUiIsCalling(phoneData.userId) && (peer.callStatus === 'webcall' || peer.callStatus === 'inner' || peer.callStatus === 'normal' || peer.callStatus === 'dialout' || peer.callStatus === 'dialTransfer' || peer.callStatus === 'transfer')) {
    dataDisabled.listen = {disabled: false, show: true}
  } else {
    dataDisabled.listen = {disabled: true, show: true}
  }
  if (peer.pbx !== phoneData.pbx_in_ip) {
    dataDisabled.loot = {disabled: true, show: false}
    dataDisabled.listen = {disabled: true, show: false}
  }
  if (!peer.sipNo) {
    dataDisabled.pick = {disabled: false, show: true}
    dataDisabled.pickGateway = {disabled: false, show: true}
    dataDisabled.kick = {disabled: true, show: true}
    dataDisabled.loot = {disabled: true, show: true}
    dataDisabled.forceHangup = {disabled: true, show: true}
    dataDisabled.listen = {disabled: true, show: true}
    dataDisabled.endlisten = {disabled: true, show: false}
  }
  return dataDisabled
}

function ctiUiIsCalling (userId) {
  var peer = window.phone_peers[userId]
  if (peer) {
    if (peer.callStatus === 'Ring' || peer.callStatus === 'Ringing' || peer.callStatus === 'inner' || peer.callStatus === 'normal' || peer.callStatus === 'dialout' || peer.callStatus === 'dialTransfer' || peer.callStatus === 'transfer' || peer.callStatus === 'listen') {
      return true
    }
  }
  return false
}
/*
 * 多渠道技能组开启自动领取座席数渲染
 * */
export function imMonitorGetQueueAutoClaimAgents (queue, newFlag) {
  if (!queue.onlineAgents) {
    imMonitorInitQueueAgents(queue)
  }
  // var autoCount = 0
  let nameList = []
  if (queue.onlineAgents.length > 0) {
    for (let i = 0; i < queue.onlineAgents.length; i++) {
      if (queue.onlineAgents[i].autoClaim || queue.onlineAgents[i].autoClaim === undefined) {
        nameList.push(queue.onlineAgents[i].name)
      }
    }
    if (nameList.length > 0) {
      var str = nameList.length + '('
      for (var i = 0; i < nameList.length; i++) {
        str += nameList[i]
        if (i !== nameList.length - 1) {
          str += ','
        }
      }
      if (newFlag) {
        let array = str.split('(')
        var nstr = array[1]
        return nstr
      }
      str += ')'
      return str
    } else {
      return '0'
    }
  } else {
    return '0'
  }
}
export function monitorWebchatConfig () {
  return {
    agentsName: m7Language('monitor.webChatAgentRemind'),
    channelName: m7Language('monitor.consultingChannelRemind'),
    serviceName: m7Language('monitor.webChatSerivceRemind'),
    agents: [
      {label: m7Language('monitor.loginAgentNum'), value: 'online'},
      {label: m7Language('monitor.loginOutAgentNum'), value: 'offline'},
      {label: m7Language('monitor.sessionIdleNum'), value: 'idle'},
      {label: m7Language('monitor.sessionBusyAgent'), value: 'busy'},
      {label: m7Language('monitor.closeSessAgentNum'), value: 'close'},
      {label: m7Language('monitor.openSessAgentNum'), value: 'open'}
    ],
    channel: [
      {label: 'web', value: 'pc'},
      {label: m7Language('monitor.weixin'), value: 'weixin'},
      {label: m7Language('monitor.weibo'), value: 'weibo'},
      {label: 'wap', value: 'wap'},
      {label: m7Language('monitor.appYiDong'), value: 'sdk'},
      {label: m7Language('monitor.applets'), value: 'wxmini'},
      {label: m7Language('webchat.enterpriseShot'), value: 'wxwork'},
      {label: m7Language('webchat.baiduBCP'), value: 'ocpc'},
      {label: m7Language('webchat.TikTok'), value: 'dy'},
      {label: m7Language('webchat.platformWXKF'), value: 'wxkf'}
    ],
    service: [
      {label: m7Language('monitor.totalAccess'), value: 'manual'},
      {label: m7Language('monitor.top5Complete'), value: 'finish'},
      {label: m7Language('monitor.waitingSessionNum'), value: 'queue'},
      {label: m7Language('monitor.activenvitation'), value: 'invite'}
    ]
  }
}
export function monitorCallConfig () {
  return {
    userName: m7Language('monitor.callAgentMonitorRemind'),
    user: [
      {label: m7Language('monitor.idleAgent'), value: 'idleUser'},
      {label: m7Language('monitor.onlineAgent'), value: 'loginUser'},
      {label: m7Language('monitor.busyAgent'), value: 'busyUser'},
      {label: m7Language('monitor.ziBusyAgent'), value: 'customUser'},
      {label: m7Language('monitor.calling'), value: 'lineingUser'}
    ],
    areaName: m7Language('monitor.inCallAreaRemind'),
    area: [
    ],
    incallName: m7Language('monitor.incomingRemind'),
    incall: [
      {label: m7Language('monitor.inCallSum'), value: 'incallTotal'},
      {label: m7Language('monitor.top5InFail'), value: 'notDealTotal'},
      {label: m7Language('monitor.top5In'), value: 'dealingTotal'},
      {label: m7Language('monitor.queueNumber'), value: 'queueTotal'},
      {label: m7Language('monitor.concurrencyimitNum'), value: 'limitTotal'}
    ],
    limitName: m7Language('monitor.concurrencyimitRemind'),
    limit: [
      {label: m7Language('monitor.concurrencyLimit'), value: 'limit'}
    ]
  }
}
export const filtersIm = {
  online (data) {
    return data.pcState || data.mobileState
  },
  free (data) {
    return (data.imDealCount - data.dealing > 0)
  },
  busy (data) {
    return data.imDealCount <= data.dealing
  },
  talking (data) {
    return data.dealing
  },
  close (data) {
    return !data.pcAutoClaim && !data.mobileAutoClaim && data.pcToggleNew === ''
  },
  customize (data) {
    return !data.pcAutoClaim && data.pcToggleNew !== ''
  }
}
export function isType (data, type) {
  return filtersIm[type](data)
}
